// ---------------------------
// 核心模块：UIManager
// ---------------------------
import { _decorator, Component, Node, instantiate, Prefab, UITransform, Size, view, error, Widget, Sprite, Color } from 'cc';
import { UIBase } from './UIBase';
import { ResLoader } from '../ResLoader';
const { ccclass, property } = _decorator;

// UI层级定义
export enum UILayerType {
    BACKGROUND = "BackgroundLayer",   // 背景层
    SCENE = "SceneLayer",             // 场景层
    NORMAL = "NormalLayer",           // 普通UI层
    POPUP = "PopupLayer",             // 弹窗层
    GUIDE = "GuideLayer",             // 引导层
    LOADING = "LoadingLayer",         // 加载层
    ALERT = "AlertLayer",             // 提示层
    TOP = "TopLayer"                  // 顶层
}

@ccclass('UIManager')
export class UIManager extends Component {
    private static _instance: UIManager;
    // UI层级容器
    private uiLayers: Map<UILayerType, Node> = new Map();

    // UI缓存池（用于对象重用）
    private uiCache: Map<string, Node> = new Map();
    
    // 活动UI列表（按层级存储）
    private activeUIs: Map<UILayerType, Node[]> = new Map();

    // UI历史记录栈（用于返回操作）
    private uiStack: Node[] = [];

    // 弹窗队列管理
    private popupQueue: Node[] = [];
    private currentPopup: Node | null = null;

    // 遮罩背景引用
    private popupBg: Node | null = null;

    public static get instance(): UIManager {
        return this._instance;
    }

    protected onLoad(): void {
        if (UIManager._instance === null) {
            UIManager._instance = this;
            this.initializeLayers();
        } else {
            this.destroy();
            return;
        }
    }

    // 初始化UI层级
    private initializeLayers(): void {
        const layerNames = (Object as any).values(UILayerType);
        for (const layer of layerNames) {
            const layerNode = new Node(layer);
            layerNode.layer = this.node.layer;
            this.node.addChild(layerNode);

            // 添加UITransform组件并设置为全屏
            const transform = layerNode.addComponent(UITransform);
            transform.setContentSize(new Size(view.getVisibleSize().width, view.getVisibleSize().height));

            // 添加Widget组件用于自适应
            const widget = layerNode.addComponent(Widget);
            widget.isAlignLeft = widget.isAlignRight = widget.isAlignTop = widget.isAlignBottom = true;
            widget.left = widget.right = widget.top = widget.bottom = 0;
            widget.alignMode = Widget.AlignMode.ON_WINDOW_RESIZE;

            this.uiLayers.set(layer, layerNode);
            this.activeUIs.set(layer, []);
        }
        // 创建遮罩节点（但不立即添加到场景）
        this.popupBg = new Node('PopupBackground');
        const sprite = this.popupBg.addComponent(Sprite);
        sprite.color = new Color(0, 0, 0, 180); // 半透明黑色背景
        const transform = this.popupBg.addComponent(UITransform);
        transform.setContentSize(new Size(2000, 2000)); // 足够大的尺寸
    }

    // 注册UI层级（可选）
    public registerLayer(layerType: UILayerType, rootNode: Node): void {
        this.uiLayers.set(layerType, rootNode);
    }

    // 显示UI
    public async showUI(uiName: string, layerType: UILayerType, data?: any): Promise<Node> {
        // 检查UI是否已存在
        if (this.activeUIs.get(layerType)?.some(ui => ui.name === uiName)) {
            console.warn(`UI ${uiName} is already shown`);
            return this.getUIByName(uiName);
        }

        let uiNode: Node | null = null;

        // 检查缓存
        if (this.uiCache.has(uiName)) {
            uiNode = this.uiCache.get(uiName);
            this.uiCache.delete(uiName);
        } else {
            // 加载UI预制体
            const prefab = await ResLoader.loadPrefab(uiName, 'ui');
            if (!prefab) {
                error(`Failed to load UI prefab: ${uiName}`);
                return null;
            }

            uiNode = instantiate(prefab);
            uiNode.name = uiName;

            // 添加UIBase组件（如果不存在）
            if (!uiNode.getComponent(UIBase)) {
                uiNode.addComponent(uiName + "_Ctrl");
            }
        }

        if (!uiNode) return null;

        // 添加到对应层级
        const layer = this.uiLayers.get(layerType);
        if (layer) {
            layer.addChild(uiNode);

            // 添加到活动UI列表
            this.activeUIs.get(layerType)?.push(uiNode);

            // 特殊处理弹窗层
            if (layerType === UILayerType.POPUP) {
                if (this.currentPopup) {
                    this.popupQueue.push(uiNode);
                    uiNode.active = false;
                } else {
                    this.currentPopup = uiNode;
                    this.showPopup(uiNode);
                }
            } else {
                uiNode.active = true;
            }

            // 调用UI初始化
            const uiBase = uiNode.getComponent(UIBase);
            if (uiBase) {
                await uiBase.onInit(data);
                await uiBase.onShow(data);
            }

            // 添加到UI栈（非弹窗）
            if (layerType !== UILayerType.POPUP && layerType !== UILayerType.LOADING) {
                this.uiStack.push(uiNode);
            }

            return uiNode;
        }

        return null;
    }

    // 隐藏UI
    public hideUI(uiName: string, destroy: boolean = false): void {
        for (const [layerType, uis] of this.activeUIs) {
            const index = uis.findIndex(ui => ui.name === uiName);
            if (index !== -1) {
                const uiNode = uis[index];

                // 移除UI
                uis.splice(index, 1);

                // 特殊处理弹窗
                if (layerType === UILayerType.POPUP && uiNode === this.currentPopup) {
                    const uiBase = uiNode.getComponent(UIBase);
                    if (uiBase) {
                        // 移除遮罩背景
                        if (this.popupBg && this.popupBg.parent) {
                            this.popupBg.removeFromParent();
                        }

                        uiBase.onHide().then(() => {
                            this.processNextPopup();
                        });
                    } else {
                        this.processNextPopup();
                    }

                    if (destroy) {
                        uiNode.destroy();
                    } else {
                        uiNode.removeFromParent();
                        this.uiCache.set(uiName, uiNode);
                    }
                } else {
                    const uiBase = uiNode.getComponent(UIBase);
                    if (uiBase) {
                        uiBase.onHide().then(() => {
                            if (destroy) {
                                uiNode.destroy();
                            } else {
                                uiNode.active = false;
                                uiNode.removeFromParent();
                                this.uiCache.set(uiName, uiNode);
                            }
                        });
                    } else {
                        if (destroy) {
                            uiNode.destroy();
                        } else {
                            uiNode.active = false;
                            uiNode.removeFromParent();
                            this.uiCache.set(uiName, uiNode);
                        }
                    }
                }

                // 从UI栈中移除
                const stackIndex = this.uiStack.indexOf(uiNode);
                if (stackIndex !== -1) {
                    this.uiStack.splice(stackIndex, 1);
                }

                return;
            }
        }
    }

    // 获取UI节点
    public getUIByName(uiName: string): Node | null {
        for (const uis of this.activeUIs.values()) {
            const ui = uis.find(n => n.name === uiName);
            if (ui) return ui;
        }
        return null;
    }

    // 清除所有UI（可选保留某些层级）
    public clearAll(exceptLayers: UILayerType[] = []): void {
        for (const [layerType, uis] of this.activeUIs) {
            if ((exceptLayers as any).includes(layerType)) continue;

            for (const ui of uis.slice()) {
                this.hideUI(ui.name, true);
            }
        }
    }

    // 显示弹窗
    private showPopup(uiNode: Node): void {
        uiNode.active = true;

        // 添加遮罩背景
        if (this.popupBg) {
            const layer = this.uiLayers.get(UILayerType.POPUP);
            if (layer) {
                layer.addChild(this.popupBg);
                this.popupBg.setSiblingIndex(0);
            }
        }

        // 播放弹窗动画
        const uiBase = uiNode.getComponent(UIBase);
        if (uiBase) {
            uiBase.playShowAnimation().then(() => {
                // 动画完成
            });
        }
    }

    // 处理下一个弹窗
    private processNextPopup(): void {
        this.currentPopup = null;

        if (this.popupQueue.length > 0) {
            const nextPopup = this.popupQueue.shift();
            if (nextPopup) {
                this.currentPopup = nextPopup;
                this.showPopup(nextPopup);

                const uiBase = nextPopup.getComponent(UIBase);
                if (uiBase) {
                    uiBase.onShow();
                }
            }
        }
    }
}
